package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.commom.Constant;
import com.itheima.reggie.commom.CustomException;
import com.itheima.reggie.commom.ResultInfo;
import com.itheima.reggie.commom.UserHolder;
import com.itheima.reggie.domain.Cart;
import com.itheima.reggie.domain.Category;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.CartMapper;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @author Sea
 * @date 2023/3/2 11:55
 */
@Service
@Transactional
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private HttpSession session;
    @Autowired
    private CartMapper cartMapper;

    @Override
    public List<Category> findAll() {
        return categoryMapper.findAll();
    }

    @Override
    public void save(Category category) {
//       long categoryId= IdUtil.createSnowflake(1,1).nextId();
//        category.setId(categoryId);
//        category.setCreateTime(new Date());
//        category.setUpdateTime(new Date());
//
//        Employee currentEmp = (Employee) session.getAttribute(Constant.SESSION_EMPLOYEE);
//        category.setCreateUser(currentEmp.getId());
//        category.setUpdateUser(currentEmp.getId());
        category.setId(IdUtil.getSnowflake(1, 1).nextId());
        categoryMapper.save(category);
    }

    @Override
    public void update(Category category) {
//        category.setUpdateTime(new Date());
//      Employee employee= (Employee) session.getAttribute(Constant.SESSION_EMPLOYEE);
//        category.setUpdateUser(employee.getId());
        categoryMapper.update(category);
    }


    @Override
    public void deleteById(Long id) {
        Integer countDish = categoryMapper.countDishByCategoryId(id);
        if (countDish > 0) {
            throw new CustomException("该分类下有菜品无法删除");
        }
        Integer countSetmeal = categoryMapper.countSetmealByCategoryId(id);
        if (countSetmeal > 0) {
            throw new CustomException("该分类下有套餐无法删除");
        }
        categoryMapper.deleteById(id);
    }

    // 根据type查询分类列表
    @Override
    public List<Category> list(Integer type) {
        // 1.构建条件  select * from category where type=1
        LambdaQueryWrapper<Category> qw = new LambdaQueryWrapper<>();
        qw.eq(Category::getType, type);
        // 2.查询
        return categoryMapper.selectList(qw);
    }




}
